package com.note.simpleshop.module.user.auth;
import java.io.BufferedReader;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.note.simpleshop.constant.ErrorCode;
import com.note.simpleshop.module.user.controller.LoginController;
import com.note.simpleshop.utils.GsonUtil;
import com.note.simpleshop.utils.ResponseUtil;
import com.note.simpleshop.utils.WebUtil;
import com.note.simpleshop.vo.Msg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
@Component
public class TokenInterceptor extends HandlerInterceptorAdapter
{
	private static final Logger log = LoggerFactory.getLogger(LoginController.class);
	@Autowired
	private TokenManager tokenManager;
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response,Object handler) throws Exception
	{
		// 判断是否是影射到方法
		if (!(handler instanceof HandlerMethod))
		{
			return true;
		}
		WebUtil.setRequest(request);
		WebUtil.setResponse(response);
		// 判断是否有requestToken,如果没有直接放行，如果有校验合法性
		HandlerMethod handlerMethod  = (HandlerMethod) handler;
		Method method = handlerMethod.getMethod();
		if (method.getAnnotation(RequestToken.class) != null)
		{
			String token = request.getHeader("token");
			if (token != null&&tokenManager.checkToken(token))
			{
				return true;
			} else
			{
				Msg msg=new Msg(ErrorCode.ERROR_1000002,"token无效或者过期");
				ResponseUtil.write(response, GsonUtil.toGson(msg));
				return false;
			}
		}
		return true;
	}

	public void postHandle(HttpServletRequest request,
			HttpServletResponse response,Object handler,
			ModelAndView modelAndView) throws Exception
	{
	}

	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response,Object handler,Exception ex)
			throws Exception
	{
	}
	public String getPostRequestBody(HttpServletRequest req) {
        if (req.getMethod().equals("POST")) {
            StringBuilder sb = new StringBuilder();
            try (BufferedReader br = req.getReader()) {
                char[] charBuffer = new char[128];
                int bytesRead;
                while ((bytesRead = br.read(charBuffer)) != -1) {
                    sb.append(charBuffer, 0, bytesRead);
                }
            } catch (IOException e) {
            	log.error(e.getMessage());
            }
            return sb.toString();
        }
        return "";
    }
}
